package cn.com.cpic.insurance.rulecheck.core.rule;

import cn.com.cpic.insurance.rulecheck.core.Context;
import cn.com.cpic.insurance.rulecheck.core.exception.BomNotFoundException;
import cn.com.cpic.insurance.rulecheck.core.exception.OperateException;
import cn.com.cpic.insurance.rulecheck.core.expression.Expression;
import cn.com.cpic.insurance.rulecheck.core.javacc.RuleCheck;

/**
 * 
 * 
 * @author 代波
 * @since 2011-8-21
 */
public class ExpressionRuleConsumer extends AbstractRuleConsumer<Boolean> {
	private static final long serialVersionUID = 3709360577419443471L;

	private Expression<Boolean> exp;
	private String expression;

	public ExpressionRuleConsumer(String token, String expression, String... tags) {
		super(token, tags);
		setExpression(expression);
	}

	public final String getExpression() {
		return expression;
	}

	public final void setExpression(String expression) {
		this.expression = expression;
		this.exp = RuleCheck.parseLogicalExpression(expression);
	}

	public final Boolean operate(Context context) throws OperateException {
		try {
			return exp.operate(context);
		} catch (BomNotFoundException e) {
			String bom = e.getBom();
			if (isRequired(bom)) {
				throw new BomNotFoundException(bom, "必须填写：" + getBomName(bom), e.getCause());
			} else {
				return true;
			}
		}
	}

	protected boolean isRequired(String bom) {
		return true;
	}

	protected String getBomName(String bom) {
		return bom;
	}
}
